package com.r2coding.auth.service;

import com.r2coding.auth.feign.UserFeignService;
import com.r2coding.auth.vo.PermissionVo;
import com.r2coding.auth.vo.UserVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author:98k灬
 * @since:2022/04/08 22:55
 **/
@Component("customerUserDetailService")
public class CustomerUserDetailService implements UserDetailsService {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    UserFeignService userFeignService;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        // return new User("admin",passwordEncoder.encode("1234"), AuthorityUtils.createAuthorityList("system"));
        if (StringUtils.isEmpty(name)) {
            throw new BadCredentialsException("用户名不能为空");
        }
        UserVo userVo = userFeignService.getByUserName(name);
        if (userVo == null) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        List<PermissionVo> permissions = userFeignService.getPermissionsByUserId(userVo.getUserId());
        List<GrantedAuthority> authorities = null;
        if (!CollectionUtils.isEmpty(permissions)) {
            authorities = new ArrayList<>();
            for (PermissionVo permission : permissions) {
                String code = permission.getCode();
                authorities.add(new SimpleGrantedAuthority(code));
            }
        }
        JwtUser jwtUser = new JwtUser();
        jwtUser.setPassword(userVo.getPassword());
        jwtUser.setUsername(userVo.getUserName());
        jwtUser.setUserId(userVo.getUserId());
        jwtUser.setAvatar(userVo.getAvatar());
        jwtUser.setPhone(userVo.getPhone());
        jwtUser.setEmail(userVo.getEmail());
        jwtUser.setSex(userVo.getSex());
        jwtUser.setAuthorities(authorities);
        return jwtUser;
    }
}
